using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using CMS.BIZ;
using System.Web;

namespace CMS.Web.UI.UserControls
{
    public class DownloadEditor : UserControl
    {
        private static string LocationOnServer = HttpContext.Current.Server.MapPath("/");
        private static string Folder = "userfiles/File/";

        protected DropDownList ddlCurrentFolder;
        protected Repeater repeaterDownloadFolder;
        protected Repeater repeaterDownload;

        private BizDownload download;
        private BizDownloadFolder folder;

        protected TextBox tbFileName;
        protected TextBox tbFileDescription;
        protected FileUpload fuFile;
        protected DropDownList ddlFolder;
        protected Button bValidateFile;
        protected Button bValidateFolder;

        public DownloadEditor()
        {
            base.Init += new EventHandler(DownloadEditor_Init);
        }

        protected string ParentFolderQueryString
        {
            get { return folder == null ? "" : folder.DownloadFolderID.ToString(); }
        }

        void DownloadEditor_Init(object sender, EventArgs e)
        {
            bValidateFile.Click += new EventHandler(ValidateFile_Click);
            bValidateFolder.Click += new EventHandler(ValidateFolder_Click);
            ddlCurrentFolder.SelectedIndexChanged += new EventHandler(CurrentFolder_SelectedIndexChanged);
            string delete = Request.QueryString["Delete"];
            string deleteFolder = Request.QueryString["DeleteFolder"];
            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(delete)) Page.BizDownloadProvider.Delete(int.Parse(delete));
                if (!string.IsNullOrEmpty(deleteFolder)) Page.BizDownloadFolderProvider.Delete(int.Parse(deleteFolder));
                if (download == null) SetDowloadFromQueryString();
                if (folder == null) SetDowloadFolderFromQueryString();
                BindFolderList();
                SetCurrentFolderFromQueryString();
                BindFolder();
                BindFile();
                if (download != null)
                {
                    tbFileDescription.Text = download.FileDescription;
                    tbFileName.Text = download.FileName;
                    if (download.ParentFolderID != null) ddlFolder.SelectedValue = download.ParentFolderID.ToString();
                    else ddlFolder.SelectedValue = "";
                    fuFile.Visible = false;
                    bValidateFolder.Visible = false;
                }
                if (folder != null)
                {
                    tbFileDescription.Text = folder.FolderDescription;
                    tbFileName.Text = folder.FolderName;
                    if (folder.ParentFolderID != null) ddlFolder.SelectedValue = folder.ParentFolderID.ToString();
                    else ddlFolder.SelectedValue = "";
                    fuFile.Visible = false;
                    bValidateFile.Visible = false;
                }
            }
        }

        private void SetCurrentFolderFromQueryString()
        {
            string str = Request.QueryString["CurrentFolder"];
            if (!string.IsNullOrEmpty(str)) ddlCurrentFolder.SelectedValue = str;
        }

        protected void ValidateFolder_Click(object sender, EventArgs e)
        {
            if (folder == null) SetDowloadFolderFromQueryString();
            bool update = true;
            if (folder == null)
            {
                update = false;
                //DateTime now = DateTime.Now;
                //BizMembershipUser user = Page.BizMembershipUser;
                //string time = now.ToString("yyyy-MM-dd-HH-mm-ss");
                //string userString;
                //if (user != null) userString = "-[" + user.MemberID.ToString() + "].";
                //else userString = "-[0" + new Random().Next() + "].";
                //string filePath = Folder + time + userString + fuFile.FileName;
                //string saveName = LocationOnServer + filePath;
                //fuFile.SaveAs(saveName);

                folder = new BizDownloadFolder();
                //download.UploadDate = now;
                //download.FilePath = filePath;
                //if (user != null) download.UploaderID = user.MemberID;
            }
            if (folder != null)
            {
                folder.FolderDescription = tbFileDescription.Text;
                folder.FolderName = tbFileName.Text;
                string folderID = ddlFolder.SelectedValue;
                if (!string.IsNullOrEmpty(folderID)) folder.ParentFolderID = int.Parse(folderID);
                if (update) Page.BizDownloadFolderProvider.Update(folder);
                else Page.BizDownloadFolderProvider.Create(folder);
                BindFolder();
                BindFolderList();
            }
        }

        private void SetDowloadFolderFromQueryString()
        {
            string str = Request.QueryString["DownloadFolder"];
            if (!string.IsNullOrEmpty(str)) folder = Page.BizDownloadFolderProvider.Read(int.Parse(str));
        }

        void CurrentFolder_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindFile();
            BindFolder();
        }

        private void BindFolder()
        {
            int? folderId = null;
            string str = ddlCurrentFolder.SelectedValue;
            if (!string.IsNullOrEmpty(str)) folderId = int.Parse(str);
            repeaterDownloadFolder.DataSource = Page.BizDownloadFolderProvider.ReadByFolder(folderId);
            repeaterDownloadFolder.DataBind();
        }

        private void BindFile()
        {
            int? folderId = null;
            string str = ddlCurrentFolder.SelectedValue;
            if (!string.IsNullOrEmpty(str)) folderId = int.Parse(str);
            repeaterDownload.DataSource = Page.BizDownloadProvider.ReadByFolder(folderId);
            repeaterDownload.DataBind();
        }

        private void BindFolderList()
        {
            ddlFolder.DataSource = Page.BizDownloadFolderProvider.ReadAll("FolderName");
            ddlCurrentFolder.DataSource = ddlFolder.DataSource;
            ddlCurrentFolder.DataTextField = ddlFolder.DataTextField = "FolderName";
            ddlCurrentFolder.DataValueField = ddlFolder.DataValueField = "DownloadFolderID";
            ddlFolder.DataBind();
            ddlCurrentFolder.DataBind();
            ddlFolder.Items.Insert(0, new ListItem("", "", true));
            ddlCurrentFolder.Items.Insert(0, new ListItem("", "", true));
            if (folder != null) ddlFolder.Items.Remove(new ListItem( folder.FolderName, folder.DownloadFolderID.ToString() ) );
        }

        private void SetDowloadFromQueryString()
        {
            string str = Request.QueryString["Download"];
            if (!string.IsNullOrEmpty(str)) download = Page.BizDownloadProvider.Read(int.Parse(str));
        }

        protected void ValidateFile_Click(object sender, EventArgs e)
        {
            if (download == null) SetDowloadFromQueryString();
            bool update = true;
            if (download == null && fuFile.Visible && fuFile.HasFile)
            {
                update = false;
                DateTime now = DateTime.Now;
                BizMembershipUser user = Page.BizMembershipUser;
                string time = now.ToString("yyyy-MM-dd-HH-mm-ss");
                string userString;
                if( user != null ) userString = "-[" + user.MemberID.ToString() + "].";
                else userString = "-[0" + new Random().Next() + "].";
                string filePath = Folder + time + userString + fuFile.FileName;
                string saveName = LocationOnServer + filePath;
                fuFile.SaveAs(saveName);

                download = new BizDownload();
                download.UploadDate = now;
                download.FilePath = filePath;
                if(user != null) download.UploaderID = user.MemberID;
            }
            if (download != null)
            {
                download.FileDescription = tbFileDescription.Text;
                download.FileName = tbFileName.Text;
                string folderID = ddlFolder.SelectedValue;
                if (string.IsNullOrEmpty(folderID)) download.ParentFolderID = null;
                else download.ParentFolderID = int.Parse(folderID);
                if (update) Page.BizDownloadProvider.Update(download);
                else Page.BizDownloadProvider.Create(download);
                BindFile();
            }
        }

    }
}
